package com.topteam.core

import org.apache.deltaspike.jpa.api.transaction.TransactionScoped

import javax.enterprise.context.ApplicationScoped
import javax.enterprise.inject.Default
import javax.enterprise.inject.Disposes
import javax.enterprise.inject.Produces
import javax.persistence.EntityManager
import javax.persistence.EntityManagerFactory
import javax.persistence.PersistenceUnit

/**
 * Created by thinkpad on 14-1-24.
 */
@ApplicationScoped
class EntityManagerProducers {
  @PersistenceUnit(unitName = "default") private var entityManagerFactory: EntityManagerFactory = _

  @PersistenceUnit(unitName = "second") private var secondEntityManagerFactory: EntityManagerFactory = _

  @Produces
  @Default
  @TransactionScoped
  def create: EntityManager = {
    return this.entityManagerFactory.createEntityManager
  }

  def dispose(@Disposes @Default entityManager: EntityManager) {
    if (entityManager.isOpen) {
      entityManager.close
    }
  }

  @Produces
  @Second
  @TransactionScoped
  def createSecond: EntityManager = {
    return this.secondEntityManagerFactory.createEntityManager
  }

  def disposeSecond(@Disposes @Second entityManager: EntityManager) {
    if (entityManager.isOpen) {
      entityManager.close
    }
  }

}
